package com.mini.demos.webgame.handler;

import java.math.BigDecimal;

import com.mini.demos.webgame.cache.CacheManager;
import com.mini.demos.webgame.entity.User;
import com.mini.demos.webgame.msg.LoginMsg;
import com.mini.demos.webgame.msg.LoginMsgResp;
import com.mini.demos.webgame.msg.MsgHead;
import com.mini.demos.webgame.util.CommandConstants;
import com.mini.demos.webgame.util.MsgSequenceId;
import com.mini.demos.webgame.util.Utils;
import com.mini.framework.communicate.mina.handler.Handler;
import com.mini.framework.communicate.mina.protocol.Msg;

public class LoginHandler extends Handler {

	@Override
	public void handle(Msg msg) {
		LoginMsg loginMsg = (LoginMsg)msg;
		User user = CacheManager.getInstance().getUserCache(loginMsg.getName());
		if(user != null){
			LoginMsgResp loginMsgResp = new LoginMsgResp();
			loginMsgResp.setCode(Integer.valueOf(0));
			loginMsgResp.setUserName(user.getLoginName());
			loginMsgResp.setNickName(user.getDisplayName());
			loginMsgResp.setSex(Integer.valueOf(0));
			loginMsgResp.setKnowledge(user.getKnowledge());
			loginMsgResp.setMoney(user.getMoney());
			
			MsgHead head = new MsgHead();
			head.setVersion((byte)0x01);
			head.setCommandId(CommandConstants.LOGIN_RESP);
			head.setSeqId(MsgSequenceId.getInstance().getSequenceId());
			Integer totalLength = CommandConstants.HEAD_LENGTH + loginMsgResp.getBodyLength().intValue();
			head.setTotalLength(totalLength.intValue());
			head.setTime(Utils.getTime());
			head.setSpace(0);
			
			loginMsgResp.setHead(head);
			msg.getSender().send(loginMsgResp);
			CacheManager.getInstance().putUserCache(user);
		}else{
			LoginMsgResp loginMsgResp = new LoginMsgResp();
			loginMsgResp.setCode(Integer.valueOf(-1));
			
			MsgHead head = new MsgHead();
			head.setVersion((byte)0x01);
			head.setCommandId(CommandConstants.LOGIN_RESP);
			head.setSeqId(MsgSequenceId.getInstance().getSequenceId());
			Integer totalLength = CommandConstants.HEAD_LENGTH + 4;
			head.setTotalLength(totalLength.intValue());
			head.setTime(Utils.getTime());
			head.setSpace(0);
			loginMsgResp.setHead(head);
			
			msg.getSender().send(loginMsgResp);
		}
	}

}
